package com.xxl.job.admin.controller;

import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.dao.IXxlJobGroupDao;
import com.xxl.job.admin.dao.IXxlJobInfoDao;
import com.xxl.job.admin.dao.IXxlJobLogDao;
import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.model.LogResult;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.rpc.netcom.NetComClientProxy;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.bigdata.framework.admin.web.controller.BaseContoroller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * index controller
 * @author xuxueli 2015-12-19 16:13:16
 */
@Controller
//@RequestMapping("/joblog")
public class JobLogController extends BaseContoroller{

	@Resource
	private IXxlJobGroupDao xxlJobGroupDao;
	@Resource
	public IXxlJobInfoDao xxlJobInfoDao;
	@Resource
	public IXxlJobLogDao xxlJobLogDao;
	// 调度日志——页面
	@RequestMapping("xxl-job-log-list.html")
	public String xxl_job_log_list(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id=request.getParameter("id");
		if(id==null){
			request.setAttribute("jobgroupiid", -1);
			request.setAttribute("jobinfoiid", -1);
		}else{
			XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(Integer.parseInt(id));
			request.setAttribute("jobgroupiid", xxlJobInfo.getJobGroup());
			request.setAttribute("jobinfoiid", xxlJobInfo.getId());
		}
		return "/modules/xxljob/xxl_job_log_list";
	}
	// 日志显示——页面
	@RequestMapping("xxl-job-log-logdetail.html")
	public String xxl_job_log_logdetail() {
		return "/modules/xxljob/xxl_job_log_logdetail";
	}
	
	//调度日志——列表
	@RequestMapping("xxljob_log_pageList")
	@ResponseBody
	public void xxljob_pageList(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Integer pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
		String jobGroupStr=request.getParameter("jobGroup");
		String jobIdStr=request.getParameter("jobId");
		String datestart=request.getParameter("datestart");
		String endstart=request.getParameter("endstart");
		Integer pageSize = 1;
		int jobId=0;
		int jobGroup=0;
		if(jobGroupStr!=null && StringUtils.isNotBlank(jobGroupStr)){
			jobGroup=Integer.parseInt(jobGroupStr);
		}
		if(jobIdStr!=null && StringUtils.isNotBlank(jobIdStr)){
			jobId=Integer.parseInt(jobIdStr);
		}
		
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		
		// parse param
		Date triggerTimeStart = null;
		Date triggerTimeEnd = null;
		if (StringUtils.isNotBlank(datestart) && StringUtils.isNotBlank(endstart)) {
			try {
				triggerTimeStart = DateUtils.parseDate(datestart, new String[]{"yyyy-MM-dd HH:mm:ss"});
				triggerTimeEnd = DateUtils.parseDate(endstart, new String[]{"yyyy-MM-dd HH:mm:ss"});
			} catch (ParseException e) {	}
		}
		
		// page query
		List<XxlJobLog> list = xxlJobLogDao.pageList((pageSize-1)*pageNumber, pageNumber, jobGroup, jobId, triggerTimeStart, triggerTimeEnd);
		int list_count = xxlJobLogDao.pageListCount((pageSize-1)*pageNumber, pageNumber, jobGroup, jobId, triggerTimeStart, triggerTimeEnd);
		
		// package result
		//Map<String, Object> maps = new HashMap<String, Object>();
	    //maps.put("recordsTotal", list_count);		// 总记录数
	   // maps.put("recordsFiltered", list_count);	// 过滤后的总记录数
	    //maps.put("data", list); 
	    // 分页列表
		StringBuffer sb = new StringBuffer();
		String result = formatToJson(list);
		sb.append("{\"listsize\":" + list.size() + ",");
		sb.append("\"pageSize\":" + (int) Math.ceil(Double.valueOf(list_count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
	    super.pringWriterToPage(sb.toString(), "application/json", response);
	}
	//调度日志——初始化执行器和任务
	@RequestMapping("xxljob_log_init")
	@ResponseBody
	public void xxljob_log_init(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String jobIdstr = request.getParameter("jobId");
		int jobId=0;
		if(jobIdstr!=null && StringUtils.isNotBlank(jobIdstr)){
			jobId=Integer.parseInt(jobIdstr);
		}
		// 执行器列表
		List<XxlJobGroup> jobGroupList =  xxlJobGroupDao.findAll();
		//model.addAttribute("JobGroupList", jobGroupList);
		// 任务
		//if (jobId > 0) {
		XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId);
			//model.addAttribute("jobInfo", jobInfo);
		//}
		StringBuffer sb = new StringBuffer();
		String jobGroup = formatToJson(jobGroupList);
		String jobGroupStr = formatToJson(jobInfo);
		sb.append("{\"jobGroup\":" + jobGroup + ",");
		sb.append("\"jobGroupsize\":" + jobGroupList.size()+",");
		sb.append("\"jobInfo\":" + jobGroupStr);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}
	//调度日志——任务列表
	@RequestMapping("xxljob_log_getJobsByGroup")
	@ResponseBody
	public void xxljob_log_getJobsByGroup(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String jobGroup = request.getParameter("jobGroup");
		List<XxlJobInfo> list = xxlJobInfoDao.getJobsByGroup(jobGroup);
		String result=formatToJson(list);
		super.pringWriterToPage(result, "application/json", response);
	}
		
	//调度日志——任务终止
	@RequestMapping("xxljob_log_logkill")
	@ResponseBody
	public void xxljob_log_logkill(HttpServletRequest request,HttpServletResponse response) throws Exception {
		// base check
		String id=request.getParameter("id");
		XxlJobLog log = xxlJobLogDao.load(Integer.parseInt(id));
		XxlJobInfo jobInfo = xxlJobInfoDao.loadById(log.getJobId());
		
		String result="";
		if (jobInfo==null) {
			result = "{\"result\":\"参数异常\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		if (ReturnT.SUCCESS_CODE != log.getTriggerCode()) {
			result = "{\"result\":\"调度失败，无法终止日志\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}

		// request of kill
		ExecutorBiz executorBiz = null;
		try {
			executorBiz = (ExecutorBiz) new NetComClientProxy(ExecutorBiz.class, log.getExecutorAddress()).getObject();
		} catch (Exception e) {
			e.printStackTrace();
			result = "{\"result\":\""+e.getMessage()+"\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
		ReturnT<String> runResult = executorBiz.kill(jobInfo.getId());

		if (ReturnT.SUCCESS_CODE == runResult.getCode()) {
			log.setHandleCode(ReturnT.FAIL_CODE);
			log.setHandleMsg("人为操作主动终止:" + (runResult.getMsg()!=null?runResult.getMsg():""));
			log.setHandleTime(new Date());
			xxlJobLogDao.updateHandleInfo(log);
			result = "{\"result\":\"ok\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		} else {
			result = "{\"result\":\""+runResult.getMsg()+"\"}";
			super.pringWriterToPage(result, "application/json", response);
			return;
		}
	}
	
	
	//调度日志——详情
	@RequestMapping("xxljob_log_logDetailPage")
	@ResponseBody
	public void xxljob_log_logDetailPage(HttpServletRequest request,HttpServletResponse response) throws Exception {
		// base check
		String id = request.getParameter("id");
		ReturnT<String> logStatue = ReturnT.SUCCESS;
		XxlJobLog jobLog = xxlJobLogDao.load(Integer.parseInt(id));
		StringBuffer sb=new StringBuffer("{");
		if (jobLog == null) {
			logStatue = new ReturnT<String>(ReturnT.FAIL_CODE, "查看执行日志失败: 日志ID非法");
		} else {
			if (ReturnT.SUCCESS_CODE != jobLog.getTriggerCode()) {
				logStatue = new ReturnT<String>(ReturnT.FAIL_CODE, "查看执行日志失败: 任务发起调度失败，无法查看执行日志");
			}
//			model.addAttribute("executorAddress", jobLog.getExecutorAddress());
//			model.addAttribute("triggerTime", jobLog.getTriggerTime().getTime());
//			model.addAttribute("logId", jobLog.getId());
			//sb.append("\"executorAddress\":\""+jobLog.getExecutorAddress()+"\",");
			//sb.append("\"triggerTime\":\""+jobLog.getTriggerTime().getTime()+"\",");
			//sb.append("\"logId\":\""+jobLog.getId()+"\",");
			sb.append("\"result\":"+formatToJson(jobLog)+",");
		}
//		model.addAttribute("logStatue", logStatue);
		String logStatueStr="{\"code\":"+logStatue.getCode()+",\"msg\":\""+logStatue.getMsg()+"\",\"content\":\""+logStatue.getContent()+"\"}";
		sb.append("\"logStatue\":"+logStatueStr+"");
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}
	//调度日志——猫
	@RequestMapping("xxljob_log_logDetailCat")
	@ResponseBody
	public void xxljob_log_logDetailCat(HttpServletRequest request,HttpServletResponse response) throws Exception {
	//public ReturnT<LogResult> logDetailCat(String executorAddress, long triggerTime, int logId, int fromLineNum){
		String executorAddress = request.getParameter("executorAddress");
		String triggerTime = request.getParameter("triggerTime");
		String logId = request.getParameter("logId");
		String fromLineNum = request.getParameter("fromLineNum");
		try {
			ExecutorBiz executorBiz = (ExecutorBiz) new NetComClientProxy(ExecutorBiz.class, executorAddress).getObject();
			ReturnT<LogResult> logResult = executorBiz.log(Long.parseLong(triggerTime), Integer.parseInt(logId), Integer.parseInt(fromLineNum));
			LogResult content = logResult.getContent();
			String logStatueStr="{\"code\":"+logResult.getCode()+",\"msg\":\""+logResult.getMsg()+"\",\"content\":"+formatToJson(content)+"}";
			
			/*
			StringBuffer sb=new StringBuffer();
			sb.append("{");
			sb.append("\"code\":");
			sb.append(logResult.getCode());
			sb.append(",\"msg\":\"");
			sb.append(logResult.getMsg());
			sb.append("\",\"content\":{\"fromLineNum\":");
			sb.append(logResult.getContent().getFromLineNum());
			sb.append(",\"toLineNum\":");
			sb.append(logResult.getContent().getToLineNum());
			sb.append(",\"logContent\":\"");
			sb.append(logResult.getContent().getLogContent());
			sb.append("\",\"isEnd\":");
			
			
			sb.append("}}");
			*/
			super.pringWriterToPage("{\"result\":\"ok\",\"info\":"+logStatueStr+"}", "application/json", response);
		} catch (Exception e) {
//			e.printStackTrace();
			String result = "{\"result\":\"no\",\"info\":\""+e.getMessage()+"\"}";
			super.pringWriterToPage(result, "application/json", response);
		}
	}
	
	/*
	@RequestMapping
	public String index(Model model, @RequestParam(required = false, defaultValue = "0") Integer jobId) {

		// 执行器列表
		List<XxlJobGroup> jobGroupList =  xxlJobGroupDao.findAll();
		model.addAttribute("JobGroupList", jobGroupList);

		// 任务
		if (jobId > 0) {
			XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId);
			model.addAttribute("jobInfo", jobInfo);
		}

		return "joblog/joblog.index";
	}

	@RequestMapping("/getJobsByGroup")
	@ResponseBody
	public ReturnT<List<XxlJobInfo>> listJobByGroup(String jobGroup){
		List<XxlJobInfo> list = xxlJobInfoDao.getJobsByGroup(jobGroup);
		return new ReturnT<List<XxlJobInfo>>(list);
	}
	
	@RequestMapping("/pageList")
	@ResponseBody
	public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start,  
			@RequestParam(required = false, defaultValue = "10") int length,
			int jobGroup, int jobId, String filterTime) {
		
		// parse param
		Date triggerTimeStart = null;
		Date triggerTimeEnd = null;
		if (StringUtils.isNotBlank(filterTime)) {
			String[] temp = filterTime.split(" - ");
			if (temp!=null && temp.length == 2) {
				try {
					triggerTimeStart = DateUtils.parseDate(temp[0], new String[]{"yyyy-MM-dd HH:mm:ss"});
					triggerTimeEnd = DateUtils.parseDate(temp[1], new String[]{"yyyy-MM-dd HH:mm:ss"});
				} catch (ParseException e) {	}
			}
		}
		
		// page query
		List<XxlJobLog> list = xxlJobLogDao.pageList(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd);
		int list_count = xxlJobLogDao.pageListCount(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd);
		
		// package result
		Map<String, Object> maps = new HashMap<String, Object>();
	    maps.put("recordsTotal", list_count);		// 总记录数
	    maps.put("recordsFiltered", list_count);	// 过滤后的总记录数
	    maps.put("data", list);  					// 分页列表
		return maps;
	}

	@RequestMapping("/logDetailPage")
	public String logDetailPage(int id, Model model){

		// base check
		ReturnT<String> logStatue = ReturnT.SUCCESS;
		XxlJobLog jobLog = xxlJobLogDao.load(id);
		if (jobLog == null) {
			logStatue = new ReturnT<String>(ReturnT.FAIL_CODE, "查看执行日志失败: 日志ID非法");
		} else {
			if (ReturnT.SUCCESS_CODE != jobLog.getTriggerCode()) {
				logStatue = new ReturnT<String>(ReturnT.FAIL_CODE, "查看执行日志失败: 任务发起调度失败，无法查看执行日志");
			}

			model.addAttribute("executorAddress", jobLog.getExecutorAddress());
			model.addAttribute("triggerTime", jobLog.getTriggerTime().getTime());
			model.addAttribute("logId", jobLog.getId());
		}

		model.addAttribute("logStatue", logStatue);
		return "joblog/logdetail";
	}

	@RequestMapping("/logDetailCat")
	@ResponseBody
	public ReturnT<LogResult> logDetailCat(String executorAddress, long triggerTime, int logId, int fromLineNum){
		try {
			ExecutorBiz executorBiz = (ExecutorBiz) new NetComClientProxy(ExecutorBiz.class, executorAddress).getObject();
			ReturnT<LogResult> logResult = executorBiz.log(triggerTime, logId, fromLineNum);
			return logResult;
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnT<LogResult>(ReturnT.FAIL_CODE, e.getMessage());
		}
	}

	@RequestMapping("/logKill")
	@ResponseBody
	public ReturnT<String> logKill(int id){
		// base check
		XxlJobLog log = xxlJobLogDao.load(id);
		XxlJobInfo jobInfo = xxlJobInfoDao.loadById(log.getJobId());
		if (jobInfo==null) {
			return new ReturnT<String>(500, "参数异常");
		}
		if (ReturnT.SUCCESS_CODE != log.getTriggerCode()) {
			return new ReturnT<String>(500, "调度失败，无法终止日志");
		}

		// request of kill
		ExecutorBiz executorBiz = null;
		try {
			executorBiz = (ExecutorBiz) new NetComClientProxy(ExecutorBiz.class, log.getExecutorAddress()).getObject();
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnT<String>(500, e.getMessage());
		}
		ReturnT<String> runResult = executorBiz.kill(jobInfo.getId());

		if (ReturnT.SUCCESS_CODE == runResult.getCode()) {
			log.setHandleCode(ReturnT.FAIL_CODE);
			log.setHandleMsg("人为操作主动终止:" + (runResult.getMsg()!=null?runResult.getMsg():""));
			log.setHandleTime(new Date());
			xxlJobLogDao.updateHandleInfo(log);
			return new ReturnT<String>(runResult.getMsg());
		} else {
			return new ReturnT<String>(500, runResult.getMsg());
		}
	}
	*/
}
